package com.store.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.store.api.model.express.ExpressVO;
import com.store.model.*;
import com.store.model.config.ApplicationEntity;
import com.store.service.*;
import com.store.utils.ConstantVariable;
import com.store.utils.FileUtil;
import com.store.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/express")
@Api(value = "获取物流数据", tags = "获取物流数据")
public class ApiExpress {


    @Autowired
    private ApplicationEntity applicationEntity;

    private Logger LOGGER = Logger.getLogger(ApiExpress.class);

    @Autowired
    private ExpressService expressService;

    @Autowired
    private OrderinfoService orderinfoService;


    @Autowired
    private ExpressinfoService expressinfoService;

    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", dataType = "String", name = "addressid", defaultValue = "地址id", value = "手机号码", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "user_lng", defaultValue = "1", value = "经度", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "user_lat", defaultValue = "1", value = "维度", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "addressdetail", defaultValue = "1", value = "详细地址", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "cityname", defaultValue = "1", value = "城市名称", required = false)})
    @ApiOperation(value = "预下单,验证订单是否可以正常发单", notes = "密")
    @ResponseBody
    @RequestMapping(value = "/sf/preCreateOrder", method = RequestMethod.GET)
    public String preCreateOrder(String addressid, String user_lng, String user_lat, String addressdetail, String cityname) {
        String expressStr = null;
        if (StringUtils.isNotBlank(addressid)) {
            expressStr = orderinfoService.validateExpressOrderTest(addressid);
        } else {
            expressStr = expressService.preCreateOrderTest(user_lng, user_lat, addressdetail, cityname, ExpressService.WEIGHT);
        }
        return ResultData.toErrorString(expressStr);
    }

    @ResponseBody
    @RequestMapping(value = "/sf/getxpressInfo", method = RequestMethod.POST)
    public String getSfExpressInfo(String orderno) {
        try {
            ExpressVO expressVO = new ExpressVO();
            ExpressinfoModel infoModel = new ExpressinfoModel();
            infoModel.setOrderno(orderno);
            infoModel.setErrorcode(0);
            List<ExpressinfoModel> dataList = expressinfoService.getList(infoModel);
            String sfOrderId = "";
            for (ExpressinfoModel model : dataList) {
                switch (model.getApitype()) {
                    case "listorderfeed":
                        List<Map<String, Object>> objList = expressService.listorderfeed(model.getSforderid(), model.getOrderno());
                        expressVO.setListorderfeed(objList);
                        break;
                    case "riderh5view":
                        expressVO.setRiderh5view(model.getContent());
                        break;
                    case "createorder":
                        sfOrderId = model.getSforderid();
                        break;
                    default:
                        break;
                }
            }

            if (StringUtils.isBlank(expressVO.getRiderh5view())) {
                expressVO.setRiderh5view(expressService.riderh5view(sfOrderId, orderno));
            }

            if (CollectionUtils.isEmpty(expressVO.getListorderfeed())) {
                expressVO.setListorderfeed(expressService.listorderfeed(sfOrderId, orderno));
            }
            return ResultData.toSuccessDataObj(expressVO);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ResultData.toErrorString();
    }

    private RegularsuborderService regularsuborderService;

    @ResponseBody
    @RequestMapping(value = "/sf/appFinshOrder")
    public String appFinshOrder(HttpServletRequest request, String orderno) {
        OrderinfoModel orderinfoModel = new OrderinfoModel();
        orderinfoModel.setOrderno(orderno);
        orderinfoModel = orderinfoService.getModelById(orderinfoModel);
        if (null == orderinfoModel) {
            RegularsuborderModel regularsuborderModel = new RegularsuborderModel();
            regularsuborderModel.setSuborderno(orderno);
            regularsuborderModel = regularsuborderService.getModelById(regularsuborderModel);
            if (null != regularsuborderModel) {
                regularsuborderModel.setStatus(ConstantVariable.ORDER_3);
                regularsuborderService.update(regularsuborderModel);
            }
        } else {
            orderinfoModel.setOrderstatus(ConstantVariable.ORDER_READY_EVAL);
            orderinfoService.update(orderinfoModel);
        }
        return ResultData.toSuccessString(orderinfoModel);
    }

    public static void main(String[] args) {
        System.out.println("{\"error_code\":3001,\"error_msg\":\"\u8ba2\u5355\u4e0d\u5b58\u5728\u3010\u8ba2\u5355\u53f7\u4e0d\u5408\u6cd5\u3011\",\"error_data\":{\"desc\":\"\u8ba2\u5355\u4e0d\u5b58\u5728\u3010\u8ba2\u5355\u53f7\u4e0d\u5408\u6cd5\u3011\"},\"result\":null}");
    }

    @Autowired
    private ExpressrecordService expressrecordService;


    @ResponseBody
    @RequestMapping(value = "/sf/finshOrder")
    public String finshOrder(HttpServletRequest request, String sign) {
        Map<String, Object> callBackMap = new HashMap<>();
        callBackMap.put("sf_order_id", "");
        callBackMap.put("shop_order_id", "");
        callBackMap.put("url_index", "");
        callBackMap.put("operator_name", "");
        callBackMap.put("rider_lng", "");
        callBackMap.put("rider_lat", "");
        callBackMap.put("order_status", "");
        callBackMap.put("status_desc", "");
        callBackMap.put("push_time", "");
        for (Map.Entry<String, Object> entry : callBackMap.entrySet()) {
            String key = entry.getKey();
            callBackMap.put(key, request.getParameter(key));
        }
        ExpressrecordModel expressrecordModel = new ExpressrecordModel();
        expressrecordModel.setRecordtext(JSON.toJSONString(callBackMap));
        expressrecordModel.setRecordtype("finshOrder");
        expressrecordModel.setOrderno(request.getParameter("shop_order_id"));
        expressrecordService.insert(expressrecordModel);
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("error_code", 0);
        returnMap.put("error_msg", "success");
        return JSON.toJSONString(returnMap);
    }


    @ResponseBody
    @RequestMapping(value = "/sf/cancelOrder", method = RequestMethod.GET)
    public String cancelOrder(String orderno) {
        return JSON.toJSONString(expressService.cancelorder(orderno));
    }

    @ResponseBody
    @RequestMapping(value = "/sf/currentEnv", method = RequestMethod.GET)
    @ApiOperation(value = "BR001:生产环境/SH001:测试环境", notes = "密")
    public String currentEnv() {
        return JSON.toJSONString(expressService.currentEnv());
    }

    @ResponseBody
    @RequestMapping(value = "/sf/switchEnv", method = RequestMethod.GET)
    @ApiOperation(value = "切换环境,dev:测试环境/pro:生产环境", notes = "密")
    public String switchEnv(String env) {
        expressService.switchEnv(env);
        return ResultData.toSuccessString();
    }

    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", dataType = "String", name = "orderno", defaultValue = "订单号", value = "订单号", required = true)})
    @ResponseBody
    @RequestMapping(value = "/sf/getExpressPosition", method = RequestMethod.GET)
    @ApiOperation(value = "切换环境,dev:测试环境/pro:生产环境", notes = "密")
    public String getExpressPosition(String orderno) {
        Map<String, Object> returnMap = expresspositionService.getExpressPosition(orderno);
        if (null == returnMap) {
            return ResultData.toErrorString();
        } else {
            return ResultData.toSuccessDataObj(returnMap);
        }
    }

    @Autowired
    private ExpresspositionService expresspositionService;

}